package com.mky.mkcompany.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mky.mkcompany.controller.domain.*;
import com.mky.mkcompany.dao.*;
import com.mky.mkcompany.exception.WafException;
import com.mky.mkcompany.model.*;
import com.mky.mkcompany.tool.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import java.util.*;

/**
 * Created by Lenovo on 2017/9/1.
 */
@Service
public class CourseManageService {
    private final Logger LOGGER = LoggerFactory.getLogger(getClass());
    @Autowired
    private QuestTypeDao questTypeDao;
    @Autowired
    private TestInfoDao testInfoDao;
    @Autowired
    private SubjectChapterDao subjectChapterDao;
    @Autowired
    private SubjectCategoryDao subjectCategoryDao;

    @Autowired
    private EntityManager em;

    @Autowired
    private TestQuestDao testQuestDao;
    @Autowired
    private PracticQuestDao practicQuestDao;
    @Autowired
    private CourseQuestDao courseQuestDao;
    @Autowired
    private CourseInfoDao courseInfoDao;
    @Autowired
    private CourseCategoryDao courseCategoryDao;
    @Autowired
    private CourseSubjectDao courseSubjectDao;

    @Autowired
    private UserDoPracticQuestDao userDoPracticQuestDao;
    @Autowired
    private UserCollectPracticQuestDao userCollectPracticQuestDao;
    @Autowired
    private UserTestDao userTestDao;
    @Autowired
    private UserDoTestDao userDoTestDao;
    @Autowired
    private UserDoTestQuestDao userDoTestQuestDao;
    @Autowired
    private UserDoTestSaveQuestDao userDoTestSaveQuestDao;
    @Autowired
    private UserCourseDao userCourseDao;
    @Autowired
    private UserDoCourseDao userDoCourseDao;
    @Autowired
    private UserDoCourseQuestDao userDoCourseQuestDao;
    @Autowired
    private UserDoCourseSaveQuestDao userDoCourseSaveQuestDao;

    public JSONObject getCourseCategoryList(String name,String examType,int page,int size){
        JSONObject res = new JSONObject();
        Sort sort=new Sort(Sort.Direction.DESC,"createTime");
        Pageable pageable = new PageRequest(page-1, size, sort);
        Page<CourseCategory> courseCategoryPage=null;
        if("all".equals(name)&&"all".equals(examType)){
            courseCategoryPage=courseCategoryDao.findAll(pageable);
        }else if(!"all".equals(name)&&!"all".equals(examType)){
            courseCategoryPage=courseCategoryDao.findByNameLikeAndExamType(name,examType,pageable);
        }else if("all".equals(name)&&!"all".equals(examType)){
            courseCategoryPage=courseCategoryDao.findByExamType(examType,pageable);
        }else if(!"all".equals(name)&&"all".equals(examType)){
            courseCategoryPage=courseCategoryDao.findByNameLike(name,pageable);
        }
        res.put("data",courseCategoryPage.getContent());
        res.put("total",courseCategoryPage.getTotalElements());
        return res;
    }

    public JSONObject saveCourseCategory(CourseCategory courseCategoryReq){
        JSONObject res = new JSONObject();
        CourseCategory courseCategoryOld=courseCategoryDao.findByNameAndExamType(courseCategoryReq.getName(),courseCategoryReq.getExamType());
        if(courseCategoryOld!=null && !courseCategoryOld.getId().equals(courseCategoryReq.getId())){
            throw new WafException("", "课程分类重复！", HttpStatus.NOT_ACCEPTABLE);
        }
        if(courseCategoryOld==null){
            CourseCategory courseCategory=new CourseCategory();
            courseCategory.setId(UUID.randomUUID().toString().replace("-",""));
            courseCategory.setName(courseCategoryReq.getName());
            courseCategory.setExamType(courseCategoryReq.getExamType());
            courseCategory.setCreateTime(DateUtil.getNowTimestamp());
            courseCategory.setUpdateTime(DateUtil.getNowTimestamp());
            courseCategoryDao.save(courseCategory);
        }else{
            courseCategoryOld.setName(courseCategoryReq.getName());
            courseCategoryOld.setExamType(courseCategoryReq.getExamType());
            courseCategoryOld.setUpdateTime(DateUtil.getNowTimestamp());
            courseCategoryDao.save(courseCategoryOld);
        }
        return res;
    }

    public void delCourseCategory(String id){
        List<CourseSubject> courseSubjectList=courseSubjectDao.findByCourseCategoryId(id);
        List<String> chapterIds=new ArrayList<>();
        for(CourseSubject courseSubject:courseSubjectList){
            chapterIds.add(courseSubject.getId());
        }
        List<CourseInfo> courseInfoList=courseInfoDao.findByCourseSubjectIdIn(chapterIds);
        List<String> courseIds=new ArrayList<>();
        for(CourseInfo courseInfo:courseInfoList){
            courseIds.add(courseInfo.getId());
        }
        if(courseIds.size()!=0){
            userDoCourseDao.deleteByCourseIds(courseIds);
            userDoCourseQuestDao.deleteByCourseIds(courseIds);
            userDoCourseSaveQuestDao.deleteByCourseIds(courseIds);
        }
        if(chapterIds.size()!=0){
            courseInfoDao.deleteByCourseSubjectIds(chapterIds);
            courseQuestDao.deleteByChapterIds(chapterIds);
        }
        courseSubjectDao.deleteByCourseCategoryId(id);
        courseCategoryDao.deleteById(id);
    }

    public JSONObject getCourseSubjectList(String examType,String courseCategoryId,int page,int size){
        JSONObject res = new JSONObject();
        Sort sort=new Sort(Sort.Direction.DESC,"createTime");
        Pageable pageable = new PageRequest(page-1, size, sort);
        Page<CourseSubject> courseSubjectPage=null;
        List<CourseSubject> courseSubjectList=new ArrayList<>();
        if("all".equals(examType)&&"all".equals(courseCategoryId)){
            courseSubjectPage=courseSubjectDao.findAll(pageable);
            courseSubjectList=courseSubjectPage.getContent();
        }else if(!"all".equals(examType)&&!"all".equals(courseCategoryId)){
            CourseCategory courseCategory=courseCategoryDao.findByExamTypeAndId(examType,courseCategoryId);
            courseSubjectList=courseSubjectDao.findByCourseCategoryId(courseCategory.getId());
        }else if("all".equals(examType)&&!"all".equals(courseCategoryId)){
            CourseCategory courseCategory=courseCategoryDao.findById(courseCategoryId);
            courseSubjectList=courseSubjectDao.findByCourseCategoryId(courseCategory.getId());
        }else if(!"all".equals(examType)&&"all".equals(courseCategoryId)){
            List<CourseCategory> courseCategories=courseCategoryDao.findByExamType(examType);
            List<String> courseCategoryIds=new ArrayList<>();
            for(CourseCategory courseCategory:courseCategories){
                courseCategoryIds.add(courseCategory.getId());
            }
            courseSubjectList=courseSubjectDao.findByCourseCategoryIdIn(courseCategoryIds);
        }
        List<String> courseCategoryIds=new ArrayList<>();
        for(CourseSubject courseSubject:courseSubjectList){
            courseCategoryIds.add(courseSubject.getCourseCategoryId());
        }
        JSONObject jsonCourseCategoryId=new JSONObject();
        List<CourseCategory> courseCategoryList=courseCategoryDao.findByIdIn(courseCategoryIds);
        for(CourseCategory courseCategory:courseCategoryList){
            jsonCourseCategoryId.put(courseCategory.getId(),courseCategory);
        }
        List<CourseSubjectRes> courseSubjectResList=new ArrayList<>();
        for(CourseSubject courseSubject:courseSubjectList){
            CourseSubjectRes courseSubjectRes=new CourseSubjectRes();
            CourseCategory courseCategory=(CourseCategory)jsonCourseCategoryId.get(courseSubject.getCourseCategoryId());
            courseSubjectRes.setExamType(courseCategory.getExamType());
            courseSubjectRes.setCourseCategoryId(courseCategory.getId());
            courseSubjectRes.setCourseCategoryName(courseCategory.getName());
            courseSubjectRes.setId(courseSubject.getId());
            courseSubjectRes.setName(courseSubject.getName());
            courseSubjectRes.setCreateTime(courseSubject.getCreateTime());
            courseSubjectRes.setUpdateTime(courseSubject.getUpdateTime());
            courseSubjectResList.add(courseSubjectRes);
        }
        int offset=(page-1)*size;
        int limit=page*size;
        int total=courseSubjectResList.size();
        if(limit>total){
            limit=total;
        }
        List<CourseSubjectRes>data=new ArrayList<>();
        if(total>0 && offset<limit) {
            data = courseSubjectResList.subList(offset, limit);
        }
        res.put("data",data);
        res.put("total",total);
        return res;
    }

    public JSONObject saveCourseSubject(CourseSubject courseSubjectReq){
        JSONObject res = new JSONObject();
        CourseSubject courseSubjectOld=courseSubjectDao.findByNameAndCourseCategoryId(courseSubjectReq.getName(),courseSubjectReq.getCourseCategoryId());
        if(courseSubjectOld!=null && !courseSubjectOld.getId().equals(courseSubjectReq.getId())){
            throw new WafException("", "课程科目名称重复！", HttpStatus.NOT_ACCEPTABLE);
        }
        if(courseSubjectOld==null){
            CourseSubject courseSubject=new CourseSubject();
            courseSubject.setId(UUID.randomUUID().toString().replace("-",""));
            courseSubject.setName(courseSubjectReq.getName());
            courseSubject.setCourseCategoryId(courseSubjectReq.getCourseCategoryId());
            courseSubject.setCreateTime(DateUtil.getNowTimestamp());
            courseSubject.setUpdateTime(DateUtil.getNowTimestamp());
            courseSubjectDao.save(courseSubject);
        }else{
            courseSubjectOld.setName(courseSubjectReq.getName());
            courseSubjectOld.setCourseCategoryId(courseSubjectReq.getCourseCategoryId());
            courseSubjectOld.setUpdateTime(DateUtil.getNowTimestamp());
            courseSubjectDao.save(courseSubjectOld);
        }
        return res;
    }

    public void delCourseSubject(String id){
        courseQuestDao.deleteByChapterId(id);
        List<CourseInfo> courseInfoList=courseInfoDao.findByCourseSubjectId(id);
        List<String> courseIds=new ArrayList<>();
        for(CourseInfo courseInfo:courseInfoList){
            courseIds.add(courseInfo.getId());
        }
        if(courseIds.size()!=0){
            userDoCourseDao.deleteByCourseIds(courseIds);
            userDoCourseQuestDao.deleteByCourseIds(courseIds);
            userDoCourseSaveQuestDao.deleteByCourseIds(courseIds);
        }
        courseInfoDao.deleteByCourseSubjectId(id);
        courseSubjectDao.deleteById(id);
    }

    public JSONObject getCourseInfoList(CourseInfoReq courseInfoReq){
        JSONObject res = new JSONObject();
        List<CourseInfo> courseInfoList=new ArrayList<>();
        if("all".equals(courseInfoReq.getExamType())&&"all".equals(courseInfoReq.getCourseCategoryId())
                &&"all".equals(courseInfoReq.getCourseSubjectId())){
            courseInfoList=courseInfoDao.findAll();
        }else if("all".equals(courseInfoReq.getExamType())&&"all".equals(courseInfoReq.getCourseCategoryId())
                &&!"all".equals(courseInfoReq.getCourseSubjectId())){
            courseInfoList=courseInfoDao.findByCourseSubjectId(courseInfoReq.getCourseSubjectId());
        }else if("all".equals(courseInfoReq.getExamType())&&!"all".equals(courseInfoReq.getCourseCategoryId())
                &&"all".equals(courseInfoReq.getCourseSubjectId())){
            CourseCategory courseCategory=courseCategoryDao.findById(courseInfoReq.getCourseCategoryId());
            List<CourseSubject> courseSubjectList=courseSubjectDao.findByCourseCategoryId(courseCategory.getId());
            List<String> courseSubjectIds=new ArrayList<>();
            for(CourseSubject courseSubject: courseSubjectList){
                courseSubjectIds.add(courseSubject.getId());
            }
            courseInfoList=courseInfoDao.findByCourseSubjectIdIn(courseSubjectIds);
        }else if("all".equals(courseInfoReq.getExamType())&&!"all".equals(courseInfoReq.getCourseCategoryId())
                &&!"all".equals(courseInfoReq.getCourseSubjectId())){
            courseInfoList=courseInfoDao.findByCourseSubjectId(courseInfoReq.getCourseSubjectId());
        }else if(!"all".equals(courseInfoReq.getExamType())&&"all".equals(courseInfoReq.getCourseCategoryId())
                &&"all".equals(courseInfoReq.getCourseSubjectId())){
            List<CourseCategory> courseCategoryList=courseCategoryDao.findByExamType(courseInfoReq.getExamType());
            List<String> courseCategoryIds=new ArrayList<>();
            for(CourseCategory courseCategory:courseCategoryList){
                courseCategoryIds.add(courseCategory.getId());
            }
            List<CourseSubject> courseSubjectList=courseSubjectDao.findByCourseCategoryIdIn(courseCategoryIds);
            List<String> courseSubjectIds=new ArrayList<>();
            for(CourseSubject courseSubject: courseSubjectList){
                courseSubjectIds.add(courseSubject.getId());
            }
            courseInfoList=courseInfoDao.findByCourseSubjectIdIn(courseSubjectIds);
        }else if(!"all".equals(courseInfoReq.getExamType())&&"all".equals(courseInfoReq.getCourseCategoryId())
                &&!"all".equals(courseInfoReq.getCourseSubjectId())){
            courseInfoList=courseInfoDao.findByCourseSubjectId(courseInfoReq.getCourseSubjectId());
        }else if(!"all".equals(courseInfoReq.getExamType())&&!"all".equals(courseInfoReq.getCourseCategoryId())
                &&"all".equals(courseInfoReq.getCourseSubjectId())){
            List<CourseSubject> courseSubjectList=courseSubjectDao.findByCourseCategoryId(courseInfoReq.getCourseCategoryId());
            List<String> courseSubjectIds=new ArrayList<>();
            for(CourseSubject courseSubject: courseSubjectList){
                courseSubjectIds.add(courseSubject.getId());
            }
            courseInfoList=courseInfoDao.findByCourseSubjectIdIn(courseSubjectIds);
        }else if(!"all".equals(courseInfoReq.getExamType())&&!"all".equals(courseInfoReq.getCourseCategoryId())
                &&!"all".equals(courseInfoReq.getCourseSubjectId())){
            courseInfoList=courseInfoDao.findByCourseSubjectId(courseInfoReq.getCourseSubjectId());
        }
        //h获取课程分类，课程科目数据。
        List<String> courseSubjectIds=new ArrayList<>();
        for(CourseInfo courseInfo:courseInfoList){
            courseSubjectIds.add(courseInfo.getCourseSubjectId());
        }
        List<CourseSubject> courseSubjectList=courseSubjectDao.findByIdIn(courseSubjectIds);
        Map<String ,CourseSubject> mapCourseSubject=new HashMap<>();
        List<String> courseCategoryIds=new ArrayList<>();
        for(CourseSubject courseSubject:courseSubjectList){
            mapCourseSubject.put(courseSubject.getId(),courseSubject);
            courseCategoryIds.add(courseSubject.getCourseCategoryId());
        }
        List<CourseCategory> courseCategoryList=courseCategoryDao.findByIdIn(courseCategoryIds);
        Map<String ,CourseCategory> mapCourseCategory=new HashMap<>();
        for(CourseCategory courseCategory:courseCategoryList){
            mapCourseCategory.put(courseCategory.getId(),courseCategory);
        }

        List<CourseInfoRes> courseInfoResList=new ArrayList<>();
        for(CourseInfo courseInfo:courseInfoList){
            CourseSubject courseSubject=mapCourseSubject.get(courseInfo.getCourseSubjectId());
            CourseCategory courseCategory=mapCourseCategory.get(courseSubject.getCourseCategoryId());
            CourseInfoRes courseInfoRes=new CourseInfoRes("createTime",2);
            courseInfoRes.setId(courseInfo.getId());
            courseInfoRes.setName(courseInfo.getName());
            courseInfoRes.setCourseSubjectId(courseInfo.getCourseSubjectId());
            courseInfoRes.setCourseSubjectName(courseSubject.getName());
            courseInfoRes.setCourseCategoryId(courseCategory.getId());
            courseInfoRes.setCourseCategoryName(courseCategory.getName());
            courseInfoRes.setExamType(courseInfo.getExamType());
            courseInfoRes.setCourseCover(courseInfo.getCourseCover());
            courseInfoRes.setUrl(courseInfo.getUrl());
            courseInfoRes.setCourseTime(courseInfo.getCourseTime());
            courseInfoRes.setSpeaker(courseInfo.getSpeaker());
            courseInfoRes.setSchedule(courseInfo.getSchedule());
            courseInfoRes.setHomework(courseInfo.getHomework());
            courseInfoRes.setCreateTime(courseInfo.getCreateTime());
            courseInfoRes.setUpdateTime(courseInfo.getUpdateTime());
            courseInfoResList.add(courseInfoRes);
        }
        Collections.sort(courseInfoResList);
        //实现分页
        int offset=(courseInfoReq.getPage()-1)*courseInfoReq.getSize();
        int limit=courseInfoReq.getPage()*courseInfoReq.getSize();
        int total=courseInfoResList.size();
        if(limit>total){
            limit=total;
        }
        List<CourseInfoRes>data=new ArrayList<>();
        if(total>0 && offset<limit) {
            data = courseInfoResList.subList(offset, limit);
        }
        res.put("data",data);
        res.put("total",total);
        return res;
    }


    public JSONObject saveCourseInfo(CourseInfo courseInfoReq){
        JSONObject res = new JSONObject();
        CourseInfo courseInfoOld=courseInfoDao.findByNameAndExamType(courseInfoReq.getName(),courseInfoReq.getExamType());
        if(courseInfoOld!=null && !courseInfoOld.getId().equals(courseInfoReq.getId())){
            throw new WafException("", "课程视频名称重复！", HttpStatus.NOT_ACCEPTABLE);
        }
        if(courseInfoOld==null){
            CourseInfo courseInfo=new CourseInfo();
            courseInfo.setId(UUID.randomUUID().toString().replace("-",""));
            courseInfo.setName(courseInfoReq.getName());
            courseInfo.setCourseSubjectId(courseInfoReq.getCourseSubjectId());
            courseInfo.setExamType(courseInfoReq.getExamType());
            courseInfo.setCourseCover(courseInfoReq.getCourseCover());
            courseInfo.setUrl(courseInfoReq.getUrl());
            courseInfo.setCourseTime(courseInfoReq.getCourseTime());
            courseInfo.setSpeaker(courseInfoReq.getSpeaker());
            courseInfo.setSchedule(courseInfoReq.getSchedule());
            courseInfo.setHomework(courseInfoReq.getHomework());
            courseInfo.setCreateTime(DateUtil.getNowTimestamp());
            courseInfo.setUpdateTime(DateUtil.getNowTimestamp());
            courseInfoDao.save(courseInfo);
        }else{
            courseInfoOld.setName(courseInfoReq.getName());
            courseInfoOld.setCourseSubjectId(courseInfoReq.getCourseSubjectId());
            courseInfoOld.setExamType(courseInfoReq.getExamType());
            courseInfoOld.setCourseCover(courseInfoReq.getCourseCover());
            courseInfoOld.setUrl(courseInfoReq.getUrl());
            courseInfoOld.setCourseTime(courseInfoReq.getCourseTime());
            courseInfoOld.setSpeaker(courseInfoReq.getSpeaker());
            courseInfoOld.setSchedule(courseInfoReq.getSchedule());
            courseInfoOld.setHomework(courseInfoReq.getHomework());
            courseInfoOld.setUpdateTime(DateUtil.getNowTimestamp());
            courseInfoDao.save(courseInfoOld);
        }
        return res;
    }

    public void delCourseInfo(String id){
        courseQuestDao.deleteByCourseId(id);
        userDoCourseDao.deleteByCourseId(id);
        userDoCourseQuestDao.deleteByCourseId(id);
        userDoCourseSaveQuestDao.deleteByCourseId(id);
        courseInfoDao.deleteById(id);
    }


    public JSONObject getCourseCategoryListXiaLa(String examType){
        JSONObject res = new JSONObject();
        List<CourseCategory> courseCategoryList=courseCategoryDao.findByExamType(examType);
        if(courseCategoryList.size()==0){
            courseCategoryList=new ArrayList<>();
        }
        res.put("data",courseCategoryList);
        return res;
    }

    public JSONObject getCourseSubjectListXiaLa(String courseCategoryId){
        JSONObject res = new JSONObject();
        List<CourseSubject> courseSubjectList=courseSubjectDao.findByCourseCategoryId(courseCategoryId);
        if(courseSubjectList.size()==0){
            courseSubjectList=new ArrayList<>();
        }
        res.put("data",courseSubjectList);
        return res;
    }

    public JSONObject getCourseInfoListXiaLa(){
        JSONObject res = new JSONObject();
        List<CourseInfo> courseInfoList=courseInfoDao.findAll();
        if(courseInfoList.size()==0){
            courseInfoList=new ArrayList<>();
        }
        res.put("data",courseInfoList);
        return res;
    }
}
